import sys
from PyQt5.QtWidgets import *
from PyQt5.QtCore import *
from qfluentwidgets import *
from PyQt5.QtGui import QFont


class ProgressDialog(QWidget):
    def __init__(self, title):
        super().__init__()
        self.titlee = title
        self.__initUI()

    def __initUI(self):
        self.progress = ProgressBar(self)
        self.vbox = QVBoxLayout()
        self.titleWidget = QLabel()

        font = QFont()
        font.setFamily("HarmonyOS Sans SC")
        font.setPointSize(11)
        self.titleWidget.setFont(font)

        self.progress.setGeometry(250, 0, 250, 25)
        self.setWindowFlags(Qt.CustomizeWindowHint | Qt.FramelessWindowHint)
        # self.cancel_button = PushButton("关闭", self)
        # self.cancel_button.clicked.connect(self.cancelProgress)

        self.titleWidget.setText(self.titlee)

        self.vbox.setContentsMargins(20, 30, 20, 20)
        self.vbox.addWidget(self.titleWidget)
        self.vbox.addWidget(self.progress)
        # self.vbox.addWidget(self.cancel_button)

        self.setLayout(self.vbox)

        self.setWindowTitle("下载任务")
        self.setGeometry(300, 300, 300, 100)

        self.timer = QBasicTimer()
        self.step = 0

        # 初始化变量用于记录鼠标位置和窗口位置
        self.offset = None
        self.origin = None

    def mousePressEvent(self, event):
        # 记录鼠标按下时的窗口位置和鼠标位置
        self.origin = self.pos()
        self.offset = event.globalPos() - self.origin

    def mouseMoveEvent(self, event):
        # 移动窗口位置
        if self.offset is not None:
            self.move(event.globalPos() - self.offset)

    def mouseReleaseEvent(self, event):
        # 清空鼠标位置信息
        self.offset = None
        self.origin = None

    def startProgress(self):
        self.step = 0
        self.progress.setValue(0)
        self.timer.start(100, self)

    def cancelProgress(self):
        self.timer.stop()
        self.close()

    def updateProgress(self, value):
        if value < 0:
            value = 0
        elif value > 100:
            value = 100
            self.close()
        self.step = value
        self.progress.setValue(self.step)
        self.titleWidget.setText(self.titlee + "  " + str(self.step) + "%")


class ProgressController(QObject):
    updateProgress = pyqtSignal(int)

    def __init__(self):
        super().__init__()

    def simulateProgress(self):
        for i in range(101):
            self.updateProgress.emit(i)
            QApplication.processEvents()
            QThread.msleep(100)  # 模拟耗时操作


if __name__ == "__main__":
    app = QApplication(sys.argv)
    dialog = ProgressDialog("下载任务")

    controller = ProgressController()
    controller.updateProgress.connect(dialog.updateProgress)

    dialog.show()
    # controller.simulateProgress()

    sys.exit(app.exec_())
